package com.jxwifi.cloud.quickclean.login;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.idroid.utils.CacheTool.MD5Util;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.InfoBean;
import com.jxwifi.cloud.quickclean.bean.SystemBean;
import com.jxwifi.cloud.quickclean.bean.WXUserInfoBean;
import com.jxwifi.cloud.quickclean.bean.WeiXinBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.AuzHttp;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.popwindow.PopCaptcha;
import com.jxwifi.cloud.quickclean.utils.CaptchaDialog;
import com.jxwifi.cloud.quickclean.utils.DetectionUtils;
import com.jxwifi.cloud.quickclean.utils.SignUtils;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import cn.trinea.android.common.util.REPattern;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.jxwifi.cloud.quickclean.R.id.captCha;

public class LoginPresenter {

    private String TAG = this.getClass().getSimpleName();
    private LoginView mView;
    private AuzImpl mAuz;
    private Context mContext;
    private CountDownTimer timer;

    private String mCustomer;//客服電話

    private IWXAPI mWxApi;
    private String captchaCode;
    private String cutImage;
    private String srcImage;
    private int xposition;
    private int yposition;
    private boolean isNewUser = false;
    public Popwindows popwindow;
    private LoginActivity loginActivty;
    private DisplayMetrics dm;
    private CaptchaDialog dialogshow;
    String verifyEffectiveToken;
    String verifyEffectiveCaptchaCode;

    public LoginPresenter(Context mContext, LoginView view,LoginActivity loginActivty) {
        this.mView = view;
        this.mContext = mContext;
        this.loginActivty = loginActivty;
        mAuz = new AuzImpl();
        //微信登录注册
        mWxApi = WXAPIFactory.createWXAPI(mContext, StateUtils.WX_APPID, false);
        // 将该app注册到微信
        mWxApi.registerApp(StateUtils.WX_APPID);
    }

    public void ChangedPhone() {
        mView.getPhone().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                TextNull();
            }
        });
    }

    public void ChangedVerification() {
        mView.getVerification().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                TextNull();
            }
        });
    }

    public void TextNull() {
        if (!TextUtils.isEmpty(mView.getPhone().getText().toString()) &&
                !TextUtils.isEmpty(mView.getVerification().getText().toString()) && mView.getIsSelection()) {
            mView.getLoginButton().setBackgroundResource(R.drawable.shap_bottom_buttom_selector);
            mView.getLoginButton().setClickable(true);
        } else {
            mView.getLoginButton().setBackgroundResource(R.drawable.shap_bottom_buttom_no);
            mView.getLoginButton().setClickable(false);
        }
    }

    public void validation() {

        isNewUserGet();

    }

    //微信登录操作
    public void wechat() {

        if (!DetectionUtils.isAvilible(mContext, StateUtils.WX_TENCENT)) {
            Toast toast = Toast.makeText(mContext, "您还未安装微信客户端", Toast.LENGTH_SHORT);
            ToastUtils.showMyToast(toast, 3000);
            return;
        } else {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "diandi_wx_login";
            mWxApi.sendReq(req);
        }
    }

    //微信登录接口返回数据
    public void requestLoginByWeChat(String code) {
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append(UrlPool.WEIXIN_OPENID)
                .append("?appid=")
                .append(StateUtils.WX_APPID)
                .append("&secret=")
                .append(StateUtils.WX_SECRET)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(loginUrl.toString())
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("fan12", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo = response.body().string();
                Log.w("weixinLogin", "数据返回 " + responseInfo);
                WeiXinBean mBean = JSON.parseObject(responseInfo, WeiXinBean.class);
                WXuserinfo(mBean.getAccess_token(), mBean.getOpenid());
            }
        });
    }

    //QQ登录
    public void getQQLogin(Object object, Tencent mTencent) {
        JSONObject obj = (JSONObject) object;
        try {
            String openID = obj.getString("openid");
            String accessToken = obj.getString("access_token");
            String expires = obj.getString("expires_in");
            mTencent.setOpenId(openID);
            mTencent.setAccessToken(accessToken, expires);
            QQToken qqToken = mTencent.getQQToken();
            UserInfo mUserInfo = new UserInfo(mContext, qqToken);
            mUserInfo.getUserInfo(new IUiListener() {
                @Override
                public void onComplete(Object o) {

                }

                @Override
                public void onError(UiError uiError) {

                }

                @Override
                public void onCancel() {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //获取微信用户信息
    public void WXuserinfo(String mAccessToken, String mOpenId) {
        String getUserInfoUrl = UrlPool.WEIXIN_USER_INFO + "?access_token=" + mAccessToken + "&openid=" + mOpenId;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(getUserInfoUrl)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("fan12", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseInfo = response.body().string();
                Log.w("LoginWX", "数据返回 " + responseInfo);
                WXUserInfoBean mInfoBean = JSON.parseObject(responseInfo, WXUserInfoBean.class);
                Map<String, String> mapParam = new HashMap<>();
                String mNonceStr = getRandom2(5);
                mapParam.put("headimgurl", mInfoBean.getHeadimgurl());
                mapParam.put("nickname", mInfoBean.getNickname());
                mapParam.put("nonceStr", mNonceStr);
                mapParam.put("sex", String.valueOf(mInfoBean.getSex()));
                mapParam.put("unionid", mInfoBean.getUnionid());
                String sign = SignUtils.createSign(mapParam, "MD5", StateUtils.SIGN_KEY, new String[]{});
                Log.w("LoginWX", "WX SIGN1  " + sign);
                sign = MD5Util.getMD5(sign+"&"+mNonceStr).toUpperCase();
                Log.w("LoginWX", "WX SIGN2  " + sign);
                loginbyWX(mInfoBean, sign, mNonceStr);
            }
        });
    }

    public void loginbyWX(WXUserInfoBean mInfoBean, String sign, String nonceStr) {
        Params params = new Params();
        params.add("nonceStr", nonceStr);
        params.add("sign", sign);
        params.add("unionid", mInfoBean.getUnionid());
        params.add("nickname", mInfoBean.getNickname());
        params.add("headimgurl", mInfoBean.getHeadimgurl());
        params.add("sex", mInfoBean.getSex());
        Log.w("LoginWX", "");
        mAuz.auzpost(UrlPool.POST_LOGIN_BY_WX, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                JSONObject obj = JSON.parseObject(data);
                String token = obj.getString("token");
                AccountMgr.puttoken(mContext, token);
                AuzHttp.KJB_APP_Token = AccountMgr.gettoken(mContext);  //token添加到请求头
                String userInfo = obj.getString("userInfo");
                InfoBean mInfoBean = JSON.parseObject(userInfo, InfoBean.class);

                Log.w("LoginWX", "login Token=" + AuzHttp.KJB_APP_Token);
                AccountMgr.putUser(mContext, mInfoBean, true);
                AccountMgr.loginSuccess(mContext);
                mView.getLoginButton().setClickable(true);
                mView.getLoginButton().setBackgroundResource(R.drawable.shap_bottom_buttom_selector);
                if (!TextUtils.isEmpty(mInfoBean.getTell())) { //微信登录判断是否有手机号，如果为空，跳转绑定手机号页面
                    mView.onSuccessIntent();
                } else {
                    mView.onSetTellIntent();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                Log.w("LoginWX", "WX errorCode  " + errorCode);
                //mView.onFailure(errorCode, msg);
            }
        });
    }


    //倒计时操作
    private void setTimerCount() {
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mView.getVer().setText("验证码(" + millisUntilFinished / 1000 + "s)");
                mView.getVer().setEnabled(false);
            }

            @Override
            public void onFinish() {
                timer.cancel();
                mView.getVer().setEnabled(true);
                mView.getVer().setText("重获验证码");
            }
        };
        timer.start();
    }

    private void SendIdentCode() {
        Params params = new Params();
        params.add("mobile", mView.getPhone().getText().toString());
        params.add("type", "CUSTOMER_LOGIN");
        mAuz.auzget(UrlPool.POST_CAPTCHA_VALIDATE, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {

            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    /**
     * 验证是否新用户
     * @return
     */
    private boolean isNewUserGet(){
        Params params = new Params();
        params.add("mobile", mView.getPhone().getText().toString());
        params.add("type", "CUSTOMER");
        mAuz.auzget(UrlPool.GET_VALIDATEUSER, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                Log.i(TAG,"isNewUserGet ==> data = "+JSON.toJSON(data));
                JSONObject jsonObject = JSONObject.parseObject(data);
                //isNewUser = jsonObject.get("newUser");
                Log.i(TAG,"isNewUserGet ==> data = "+jsonObject.get("newUser"));

                if(jsonObject.get("newUser").equals(true)){
                    Log.i(TAG,"isNewUserGet ==> 新用户data = "+jsonObject.get("newUser"));
                    getVrifyImage();
                    //popCaptcha(mContext,captchaCode,cutImage,srcImage,xposition,yposition);

                }else{
                    loginActivty.mLoadDialog.dismiss();
                    Log.i(TAG,"isNewUserGet ==> 老用户data = "+jsonObject.get("newUser"));
                    setTimerCount();
                    String token = jsonObject.get("token").toString();
                    validateShortLetter(token,captchaCode);
                }

            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
                loginActivty.mLoadDialog.dismiss();
                Log.i(TAG,"isNewUserGet ==> msg = "+msg+"请检查网络重试");
            }
        });


        return isNewUser;
    }

    /**
     * 验证图片是否成功
     * @param xposition
     */
    public void verifyEffective(int xposition){
        Params params = new Params();
        params.add("captchaCode", captchaCode);
        Log.i(TAG,"verifyEffective ==> xposition = "+xposition);
        params.add("xPosition", xposition);
        mAuz.auzget(UrlPool.GET_VERIFYIEDDEXTIVE, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                Log.i(TAG,"isNewUserGet ==> data = "+JSON.toJSON(data));
                JSONObject jsonObject = JSONObject.parseObject(data);
                //isNewUser = jsonObject.get("newUser");
                Log.i(TAG,"verifyEffective ==>拼图验证成功 ");
                loginActivty.mLoadDialog.dismiss();
                Log.i(TAG,"verifyEffective ==> data = "+jsonObject.get("token"));
                verifyEffectiveToken = jsonObject.get("token").toString();
                verifyEffectiveCaptchaCode = jsonObject.get("captchaCode").toString();
                Toast.makeText(mContext, "验证成功", Toast.LENGTH_SHORT).show();
                dialogshow.dismiss();
                successValidateShortLetter();

            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
                loginActivty.mLoadDialog.dismiss();
                //Toast.makeText(mContext, errorCode+": "+msg, Toast.LENGTH_SHORT).show();
                //getVrifyImage();
                if (errorCode == 409){
                    Toast.makeText(mContext, "图形验证码过期，请重新获取", Toast.LENGTH_SHORT).show();
                    dialogshow.dismiss();
                }else{
                    dialogshow.reset();
                }
                Log.i(TAG,"verifyEffective ==>AuzFailure  msg = "+msg);
            }
        });
    }

    public void successValidateShortLetter(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setTimerCount();
                validateShortLetter(verifyEffectiveToken,verifyEffectiveCaptchaCode);
            }
        }, 1000);
    }

    /**
     * 请求短信验证码
     * @param token
     */
    private void validateShortLetter(String token,String captchaCode){
        Params params = new Params();
        params.add("mobile", mView.getPhone().getText().toString());
        params.add("token", token);
        params.add("type","CUSTOMER_LOGIN");
        mAuz.auzget(UrlPool.GET_VALIDATESHORTLETTER, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                Log.i(TAG,"isNewUserGet ==> data = "+JSON.toJSON(data));
                JSONObject jsonObject = JSONObject.parseObject(data);
                //isNewUser = jsonObject.get("newUser");
                Log.i(TAG,"validateShortLetter ==>请求短信验证码 ");
                //Log.i(TAG,"validateShortLetter ==> data = "+jsonObject.get("msg"));
                //String token = jsonObject.get("token").toString();
                Toast.makeText(mContext, "发送成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
                Log.i(TAG,"validateShortLetter ==>AuzFailure  msg = "+msg);
                Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }



    public void judge() {

        logining();
    }

    public void logining() {
        mView.getLoginButton().setClickable(false);
        mView.getLoginButton().setBackgroundResource(R.drawable.shap_bottom_buttom_no);
        Params params = new Params();
        params.add("code", mView.getVerification().getText().toString());
        params.add("tell", mView.getPhone().getText().toString());
        mAuz.auzget(UrlPool.CLEANER_LOGIN, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                JSONObject obj = JSON.parseObject(data);
                String token = obj.getString("token");
                AccountMgr.puttoken(mContext, token);
                AuzHttp.KJB_APP_Token = AccountMgr.gettoken(mContext);  //token添加到请求头
                String userInfo = obj.getString("userInfo");
                InfoBean mInfoBean = JSON.parseObject(userInfo, InfoBean.class);
                if ("Y".equals(mInfoBean.getIsFreeze())) { //用户被冻结后提示不保存数据，不做登录记录
                    new AlertDialog.Builder(mContext)
                            .setTitle("账户信息提醒")//定位服务已关闭
                            .setMessage("您的账号已被冻结，请联系客服")
                            .setPositiveButton("拨打客服电话", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //前往应用详情界面
                                    inittell();
                                    dialog.dismiss();
                                }
                            }).create().show();
                    return;
                }
                Log.w("oushuhua", "login Token=" + AuzHttp.KJB_APP_Token);
                AccountMgr.putUser(mContext, mInfoBean, true);
                AccountMgr.loginSuccess(mContext);
                mView.getLoginButton().setClickable(true);
                mView.getLoginButton().setBackgroundResource(R.drawable.shap_bottom_buttom_selector);
                mView.onSuccessIntent();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void inittell() {
        mAuz.auzget(UrlPool.SYSTEM_LIST, new Params(), new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                List<SystemBean> msystemBean = JSON.parseArray(data, SystemBean.class);
                for (int i = 0; i < msystemBean.size(); i++) {
                    if ("kjb_ke_tell".equals(msystemBean.get(i).getKeyName())) {
                        mCustomer = msystemBean.get(i).getKeyValue();
                        break;
                    }
                }
                if (!TextUtils.isEmpty(mCustomer)) {
                    Intent mTelintent = new Intent(Intent.ACTION_DIAL);
                    Uri Urldata = Uri.parse("tel:" + mCustomer.replace("\\", ""));
                    mTelintent.setData(Urldata);
                    mContext.startActivity(mTelintent);
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public static String getRandom2(int len) {
        Random r = new Random();
        StringBuilder rs = new StringBuilder();
        for (int i = 0; i < len; i++) {
            rs.append(r.nextInt(10));
        }
        return rs.toString();
    }

    /**
     * 获取验证码图片
     */
    public void getVrifyImage(){
        Params params = new Params();
        mAuz.auzget(UrlPool.GET_VERIFYIMAGE, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                Log.i(TAG,"getVrifyImage() ==> data = "+JSON.toJSON(data));
                JSONObject jsonObject = JSONObject.parseObject(data);
                captchaCode = jsonObject.get("captchaCode").toString();
                cutImage = jsonObject.get("cutImage").toString();
                srcImage = jsonObject.get("srcImage").toString();
                xposition = Integer.parseInt(jsonObject.get("xposition").toString());
                yposition = Integer.parseInt(jsonObject.get("yposition").toString());
                loginActivty.mLoadDialog.dismiss();

                Log.i(TAG,"getVrifyImage ==>  yposition = "+yposition+" xposition = "+xposition);

                dm = mContext.getResources().getDisplayMetrics();
                Log.i(TAG, "屏幕尺寸： width = "+dm.widthPixels +" height = "+dm.heightPixels+" density = "+dm.densityDpi+" int ypositon = "+(int)(yposition * dm.densityDpi * 0.007));
                dialogshow = new CaptchaDialog(mContext, captchaCode, cutImage, srcImage, xposition,(int)(yposition * dm.densityDpi * 0.0069),dm.densityDpi, new CaptchaDialog.CaptchaDialogListner() {
                    @Override
                    public void getX(int X) {
                        loginActivty.mLoadDialog.show();
                        verifyEffective((int)(X * 10000 / 69 / dm.densityDpi));
                        //Log.i(TAG,"isNewUserGet ==> verifyEffective X = "+X+" densityDpi x = "+(int)(X * dm.densityDpi / 1241.87));
                        Log.i(TAG,"isNewUserGet ==> verifyEffective X = "+X+" densityDpi x = "+(int)(X * 10000 / 69 / dm.densityDpi));
                    }

                    @Override
                    public void refresh() {
                        //点击刷新按钮
                        //getVrifyImage();
                        dialogshow.notify();
                    }

                });
                dialogshow.setCancelable(false);
                dialogshow.show();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {

                mView.onFailure(errorCode, msg);
                loginActivty.mLoadDialog.dismiss();
                Log.i(TAG,"getVrifyImage ==>AuzFailure  msg = "+msg);
            }
        });
    }

    /**
     *滑动拼图弹框
     */
    public void popCaptcha(Context mContext,String captchaCode, String cutImage, String srcImage, int xposition, int yposition){
        PopCaptcha popCaptcha = new PopCaptcha(mContext,captchaCode, cutImage, srcImage, xposition, yposition, new PopCaptcha.PopCaptchatListener() {
            @Override
            public void dissPop() {
                WindowManager.LayoutParams lp = loginActivty.getWindow().getAttributes();
                lp.alpha = 1f;
                loginActivty.getWindow().setAttributes(lp);
            }
        });
        popwindow = PopWindowUtil.getPopupWindow(popCaptcha.getView(), ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup
                .LayoutParams.MATCH_PARENT);
        popCaptcha.setPopwindow(popwindow);
        popwindow.show(mView.getLoginImages(),Popwindows.Location.BOTTOM);
        WindowManager.LayoutParams lp = loginActivty.getWindow().getAttributes();
        lp.alpha = 0.7f;
        loginActivty.getWindow().setAttributes(lp);
        //popwindow.showAtLocation(loginActivty.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


}
